home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Info-Mac 1992 August
/
info-mac-1992.iso
/
Applications (app)
/
STvi
/
stevie 3.10
/
malloc.c
< prev
next >
Wrap
Text File
|
1991-01-04
|
2KB
|
111 lines
/*
* Malloc() and free() for use with Stevie for the Mac.
*
* Earle R. Horton, November 21, 1989
*
* Source: These routines are for the most part adaptations of
* the storage allocator example program from pages 173-177
* of "The C Programming Language" by Brian Kernighan and
* Dennis M. Ritchie, Prentice-Hall Software Series, 1978
*
*/
#include <Memory.h>
#define safety 65000L
#ifndef NULL
#define NULL 0L
#endif
typedef long ALIGN;
union header{
struct{
union header *ptr;
unsigned long size;
} s;
ALIGN x;
};
typedef union header HEADER;
static HEADER base;
static HEADER *allocp = NULL;
char *lmalloc(nbytes)
unsigned long nbytes;
{
HEADER *morecore();
register HEADER *p,*q;
register long nunits;
nunits = 1+(nbytes+sizeof(HEADER)-1)/sizeof(HEADER);
if ((q = allocp) == NULL){
base.s.ptr = allocp = q = &base;
base.s.size = 0;
}
for(p = q->s.ptr; ;q=p, p=p->s.ptr){
if(p->s.size >= nunits){
if(p->s.size == nunits)
q->s.ptr = p->s.ptr;
else{
p->s.size -= nunits;
p += p->s.size;
p->s.size = nunits;
}
allocp = q;
return((char *)(p + 1));
}
if (p == allocp)
if ((p = morecore(nunits))==NULL){
emsg("malloc() failed!");
return(NULL);
}
}
}
char *malloc(nbytes)
unsigned int nbytes;
{
return lmalloc((long)nbytes);
}
#define NALLOC 128
static HEADER *morecore(nu)
unsigned long nu;
{
char *sbrk();
register char *cp;
register HEADER *up;
register long rnu;
register long s;
if(FreeMem() < safety) return NULL;
rnu = NALLOC * ((nu+NALLOC-1)/NALLOC);
cp = NewPtr(rnu*sizeof(HEADER));
if(cp == NULL) return NULL;
up = (HEADER *)cp;
up->s.size = rnu;
free((char *)(up + 1));
return(allocp);
}
free(ap)
char *ap;
{
register HEADER *p,*q;
if(ap){
p = (HEADER *)ap - 1;
for (q = allocp; !(p > q && p < q->s.ptr); q = q->s.ptr)
if (q >= q->s.ptr && (p > q || p < q->s.ptr))
break;
if (p + p->s.size == q->s.ptr){
p->s.size += q->s.ptr->s.size;
p->s.ptr = q->s.ptr->s.ptr;
}
else
p->s.ptr = q->s.ptr;
if (q + q->s.size == p){
q->s.size += p->s.size;
q->s.ptr = p->s.ptr;
}
else
q->s.ptr = p;
allocp = q;
}
}